<template>
  <view class="coupon-page">
    <!-- 顶部标签栏 -->
    <view class="tab-bar">
      <view 
        :class="['tab-item', currentTab === 0 ? 'active' : '']" 
        @click="switchTab(0)"
      >
        未使用({{ unusedCoupons.length }})
      </view>
      <view 
        :class="['tab-item', currentTab === 1 ? 'active' : '']" 
        @click="switchTab(1)"
      >
        使用记录({{ usedCoupons.length }})
      </view>
      <view 
        :class="['tab-item', currentTab === 2 ? 'active' : '']" 
        @click="switchTab(2)"
      >
        已过期({{ expiredCoupons.length }})
      </view>
    </view>

    <!-- 内容区域，根据 tab 切换显示 -->
    <view class="tab-content">
      <!-- 未使用 -->
      <view v-if="currentTab === 0" class="coupon-list">
        <view v-if="unusedCoupons.length === 0" class="empty-state">
          <text>暂无未使用的优惠券</text>
        </view>
        <view 
          class="coupon-item" 
          v-for="(item, index) in unusedCoupons" 
          :key="index"
        >
          <view class="coupon-left">
            <view class="coupon-type">{{ item.couponRange || '平台' }}</view>
            <view class="coupon-desc">{{ item.couponContent || '全场通用(特殊商品除外)' }}</view>
            <view class="coupon-time">有效期至{{ formatDate(item.couponEndTime) }}</view>
          </view>
          <view class="coupon-right">
            <view v-if="item.couponType === '满减券'" class="coupon-amount">¥{{ item.couponMoney }}</view>
            <view v-else-if="item.couponType === '折扣券'" class="coupon-amount">{{ (item.couponDiscount * 10).toFixed(0) }}折</view>
            <view class="coupon-condition">满{{ item.couponDoorsill }}元可用</view>
            <button class="use-btn" @click="useCoupon(item)">立即使用</button>
          </view>
        </view>
      </view>
      
      <!-- 使用记录 -->
      <view v-else-if="currentTab === 1" class="record-list">
        <view v-if="usedCoupons.length === 0" class="empty-state">
          <text>暂无使用记录</text>
        </view>
        <view 
          class="coupon-item used" 
          v-for="(item, index) in usedCoupons" 
          :key="index"
        >
          <view class="coupon-left">
            <view class="coupon-type">{{ item.couponRange || '平台' }}</view>
            <view class="coupon-desc">{{ item.couponContent || '全场通用(特殊商品除外)' }}</view>
            <view class="coupon-time">使用时间：{{ formatDate(item.useTime) }}</view>
          </view>
          <view class="coupon-right">
            <view v-if="item.couponType === '满减券'" class="coupon-amount">¥{{ item.couponMoney }}</view>
            <view v-else-if="item.couponType === '折扣券'" class="coupon-amount">{{ (item.couponDiscount * 10).toFixed(0) }}折</view>
            <view class="coupon-condition">满{{ item.couponDoorsill }}元可用</view>
            <view class="used-tag">已使用</view>
          </view>
        </view>
      </view>
      
      <!-- 已过期 -->
      <view v-else-if="currentTab === 2" class="expired-list">
        <view v-if="expiredCoupons.length === 0" class="empty-state">
          <text>暂无已过期优惠券</text>
        </view>
        <view 
          class="coupon-item expired" 
          v-for="(item, index) in expiredCoupons" 
          :key="index"
        >
          <view class="coupon-left">
            <view class="coupon-type">{{ item.couponRange || '平台' }}</view>
            <view class="coupon-desc">{{ item.couponContent || '全场通用(特殊商品除外)' }}</view>
            <view class="coupon-time">已过期：{{ formatDate(item.couponEndTime) }}</view>
          </view>
          <view class="coupon-right">
            <view v-if="item.couponType === '满减券'" class="coupon-amount">¥{{ item.couponMoney }}</view>
            <view v-else-if="item.couponType === '折扣券'" class="coupon-amount">{{ (item.couponDiscount * 10).toFixed(0) }}折</view>
            <view class="coupon-condition">满{{ item.couponDoorsill }}元可用</view>
            <view class="expired-tag">已过期</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { getUserId } from '../../utils/auth';
import { userCouponApi } from '../../utils/csmshopApi';

export default {
  data() {
    return {
      currentTab: 0, // 当前选中标签，0-未使用、1-使用记录、2-已过期
      userId: Number(getUserId()),
      loading: false,
      allCoupons: [], // 所有优惠券数据
      unusedCoupons: [], // 未使用优惠券
      usedCoupons: [], // 已使用优惠券
      expiredCoupons: [] // 已过期优惠券
    };
  },
  
  onLoad() {
    this.loadUserCoupons();
  },
  
  methods: {
    // 切换标签
    switchTab(tabIndex) {
      this.currentTab = tabIndex;
    },
    
    // 加载用户优惠券数据
    async loadUserCoupons() {
      if (!this.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      try {
        const response = await userCouponApi.getUserCouponList(this.userId);
        if (response.code === 200) {
          this.allCoupons = response.data || [];
          this.categorizeCoupons();
        } else {
          uni.showToast({
            title: response.msg || '获取优惠券失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取优惠券失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 分类优惠券
    categorizeCoupons() {
      this.unusedCoupons = [];
      this.usedCoupons = [];
      this.expiredCoupons = [];
      
      this.allCoupons.forEach(coupon => {
        if (coupon.status === 'used') {
          this.usedCoupons.push(coupon);
        } else if (coupon.status === 'expired' || coupon.isExpired) {
          this.expiredCoupons.push(coupon);
        } else {
          this.unusedCoupons.push(coupon);
        }
      });
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 使用优惠券
    useCoupon(coupon) {
      let message = '';
      if (coupon.couponType === '满减券') {
        message = `使用优惠券：满${coupon.couponDoorsill}减${coupon.couponMoney}`;
      } else if (coupon.couponType === '折扣券') {
        message = `使用优惠券：${(coupon.couponDiscount * 10).toFixed(0)}折优惠`;
      } else {
        message = '使用优惠券';
      }
      
      uni.showToast({
        title: message,
        icon: 'none'
      });
      
      // 这里可以跳转到商品页面或订单页面
      // uni.navigateTo({
      //   url: '/pages/product/product'
      // });
    },
    
    // 下拉刷新
    onPullDownRefresh() {
      this.loadUserCoupons().then(() => {
        uni.stopPullDownRefresh();
      });
    }
  }
};
</script>

<style scoped>
.coupon-page {
  padding: 10px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.tab-bar {
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  color: #666;
  font-size: 14px;
  position: relative;
}

.tab-item.active {
  color: #ff3333;
  background-color: #fff5f5;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background-color: #ff3333;
}

.tab-content {
  background-color: #fff;
  border-radius: 8px;
  min-height: 200px;
}

.coupon-list, .record-list, .expired-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
}

.coupon-item {
  display: flex;
  flex-direction: row;
  padding: 15px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
}

.coupon-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(to bottom, #ff3333, #ff6666);
}

.coupon-item.used::before {
  background: #999;
}

.coupon-item.expired::before {
  background: #ccc;
}

.coupon-left {
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;
}

.coupon-type {
  color: #ff3333;
  font-size: 12px;
  margin-bottom: 8px;
  font-weight: bold;
}

.coupon-desc {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.coupon-time {
  font-size: 12px;
  color: #999;
}

.coupon-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-width: 80px;
}

.coupon-amount {
  font-size: 20px;
  color: #ff3333;
  font-weight: bold;
  margin-bottom: 8px;
}

.coupon-condition {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  text-align: center;
}

.use-btn {
  background-color: #ff3333;
  color: #fff;
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 15px;
  border: none;
  min-width: 60px;
}

.used-tag, .expired-tag {
  background-color: #999;
  color: #fff;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 10px;
  text-align: center;
}

.expired-tag {
  background-color: #ccc;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .coupon-item {
    padding: 12px;
  }
  
  .coupon-amount {
    font-size: 18px;
  }
  
  .coupon-desc {
    font-size: 13px;
  }
}
</style>